package zhihui.mobile.net;

import android.util.Log;

import com.zgm.utils.AesKit;

import org.apache.log4j.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;
import java.util.Map;

import zhihui.mobile.bean.token.TokenInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.interfaces.net.IHttpCallBackListener;
import zhihui.mobile.manager.token.TokenManager;

/**
 * Created by 张公铭 on 2017/6/28 0028.
 */

public class HttpUtils
{
    private static Logger logger = Logger.getLogger(HttpUtils.class);
    private static final String http_error = "服务器忙，请稍后重试！";

    public static void get(String url, Map<String, Object> params, final IHttpCallBackListener listener)
    {
        logger.debug("url:" + url);
        RequestParams request = new RequestParams(url);
        request.setConnectTimeout(10 * 1000);
        if (params != null)
        {
            for (String key : params.keySet())
            {
                request.addParameter(key, params.get(key));
            }
        }
        x.http().get(request, new Callback.CommonCallback<JSONObject>()
        {
            @Override
            public void onSuccess(JSONObject result)
            {
                Log.i("xxx", "success");
                logger.debug("result :" + result.toString());
                listener.success(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback)
            {
                Log.i("xxx", "onError");
                logger.error("onError :" + ex.getMessage() + "---" + isOnCallback);
                listener.failed(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex)
            {
                Log.i("xxx", "onCancelled");
                logger.error("onCancelled :" + cex.getMessage());
                listener.failed(cex.getMessage());
            }

            @Override
            public void onFinished()
            {
                logger.info("onFinished!");
                Log.i("xxx", "http_finished");
            }
        });
    }


    public static void post(String url, Map<String, Object> params, final IHttpCallBackListener listener)
    {
        RequestParams request = new RequestParams(url);
        request.setConnectTimeout(10 * 1000);
        if (params != null)
        {
            for (String key : params.keySet())
            {
                request.addParameter(key, params.get(key));
            }
        }
        x.http().post(request, new Callback.CommonCallback<JSONObject>()
        {
            @Override
            public void onSuccess(JSONObject result)
            {
                logger.debug("result :" + result.toString());
                listener.success(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback)
            {
                logger.error("onError :" + ex.getMessage());
                listener.failed(http_error);
            }

            @Override
            public void onCancelled(CancelledException cex)
            {
                logger.error("onCancelled :" + cex.getMessage());
                listener.failed(http_error);
            }

            @Override
            public void onFinished()
            {
                logger.info("onFinished!");
            }
        });
    }

    public static void postFile(final String url, String userId, String file, final IHttpCallBackListener listener)
    {
        RequestParams params = new RequestParams(url);
        params.addParameter("userid", userId);
        params.setMultipart(true);
        params.addBodyParameter("file", new File(file));
        x.http().post(params, new Callback.CommonCallback<JSONObject>()
        {
            public void onSuccess(JSONObject result)
            {
                logger.debug("result :" + result.toString());
                try
                {
                    String state = result.getString("state");
                    String msg = result.getString("msg");
                    if (state.equals(Config.SUCCESS))
                    {
                        listener.success(result);
                    } else if (state.equals("token"))
                    {
                        TokenManager.getInstance().setCurToken(null);
                        listener.failed("网络超时,请重新尝试...");
                    } else
                    {
                        listener.failed(msg);
                    }
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    listener.failed("json数据解析错误：" + e.getMessage());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback)
            {
                logger.error("onError :" + ex.getMessage() + "---" + isOnCallback);
                if (!isOnCallback)
                {
                    listener.failed(http_error);
                }
            }

            @Override
            public void onCancelled(CancelledException cex)
            {
                logger.error("onCancelled :" + cex.getMessage());
                listener.failed(http_error);
            }

            @Override
            public void onFinished()
            {
                logger.info("onFinished!");
            }
        });
    }

    public static void postAes(final String url, final Map<String, String> params, final List<Object> values, final IHttpCallBackListener listener)
    {
        //token 为null 获取token
        if (TokenManager.getInstance().getCurToken() == null)
        {
            boolean result = TokenManager.getInstance().getToken();
            Log.d("xxx", "token null result :" + result);
            if (!result)
            {
                listener.failed("网络超时,请重新尝试...");
                return;
            }
        } else      //不为null,判断是否超时，超时重新获取
        {
            if (!TokenManager.getInstance().checkToken())
            {
                boolean result = TokenManager.getInstance().getToken();
                Log.d("xxx", "token timeout result :" + result);
                if (!result)
                {
                    listener.failed("网络超时,请重新尝试...");
                    return;
                }
            }
        }

            params.put("token", TokenManager.getInstance().getCurToken().getUuid());
            RequestParams request = new RequestParams(url);
            request.setConnectTimeout(10 * 1000);
            JSONObject json = new JSONObject();
            try
            {
                if (params != null)
                {
                    for (String key : params.keySet())
                    {
                        json.put(key, params.get(key));
                    }
                }

                JSONArray ary = new JSONArray();
                if (values != null)
                {
                    for (Object obj : values)
                    {
                        ary.put(obj);
                    }
                }

                json.put("paramValue", ary);

                String jsonStr = json.toString();
                logger.debug("jsonStr:" + jsonStr);

                TokenInfo curToken = TokenManager.getInstance().getCurToken();
                logger.debug("paramValue :" + jsonStr);
                request.addParameter("param", curToken.getUuid() + AesKit.encryptAES(jsonStr, curToken.getUuid().substring(curToken.getLength(), curToken.getLength() + 16)));
                x.http().post(request, new Callback.CommonCallback<JSONObject>()
                {
                    public void onSuccess(JSONObject result)
                    {
                        logger.debug("result :" + result.toString());
                        try
                        {
                            String state = result.getString("state");
                            String msg = result.getString("msg");
                            if (state.equals(Config.SUCCESS))
                            {
                                listener.success(result);
                            } else if (state.equals("token"))
                            {
                                TokenManager.getInstance().setCurToken(null);
                                listener.failed("网络超时,请重新尝试...");
                            } else
                            {
                                listener.failed(msg);
                            }
                        } catch (JSONException e)
                        {
                            e.printStackTrace();
                            listener.failed("json数据解析错误：" + e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback)
                    {
                        logger.error("onError :" + ex.getMessage() + "---" + isOnCallback);
                        if (!isOnCallback)
                        {
                            listener.failed(http_error);
                        }
                    }

                    @Override
                    public void onCancelled(CancelledException cex)
                    {
                        logger.error("onCancelled :" + cex.getMessage());
                        listener.failed(http_error);
                    }

                    @Override
                    public void onFinished()
                    {
                        logger.info("onFinished!");
                    }
                });
            } catch (Exception e)
            {
                logger.error("getAes exception :" + e.getMessage());
                e.printStackTrace();
                listener.failed(e.getMessage());
            }
        }
    }
